<template>
    <el-container style="margin: 0 3px">



                           


        <el-main style="margin: 3px 3px">
            <!--
            <el-row style="margin: 5px">
                <el-col :span="12">
                    当前任务:
                </el-col>
                <el-col :span="12">
                    {{ taskModel.name }}
                </el-col>
            </el-row>
            -->
            <el-row>
                <!--
                <el-col :span="6">
                    <el-button size="mini" @click="newHandler"><i class="iconfont el-icon-document-add"></i></el-button>
                </el-col><i class="fa-solid fa-floppy-disk-circle-arrow-right"></i><i class="iconfont iconimport"></i><i class="iconfont iconexport"></i>
                -->
                <el-col :span="6">
                    <el-button size="mini"  @click="importHandler"><i class="fa fa-file-import"></i></el-button>
                </el-col>
                <el-col :span="6">
                    <el-button size="mini" @click="exportHandler"><i class="fa fa-save"></i></el-button>
                </el-col>
                <el-col :span="6">
                    <el-button size="mini" @click="removeAll"><i class="fa fa-trash"></i></el-button>
                </el-col>
            </el-row>

<el-dialog title="输入名称" :visible.sync="taskDialogVisible" append-to-body>
                                <el-input v-model="newName" autocomplete="off"></el-input>
                                <div slot="footer" class="dialog-footer">
                                    <el-button @click="taskDialogVisible = false">取 消</el-button>
                                    <el-button type="primary" @click="renameAction()">确 定</el-button>
                                </div>
                            </el-dialog>

                            
 <div id="popmenu" class="popmenu" v-if="showpopupmenu" :style="{left:left + 'px',top:top + 'px'}"  >
<el-button  size="mini" style="margin:0" v-for="tool in tools" :key="tool.id" @click="tool.action()">
                            <i class="iconfont action-item" :class="[tool.icon]"></i>
                        </el-button>


                            </div>


            <el-tree style="max-height:25vh" :data="json" show-checkbox node-key="id" ref="tree"  @node-click="ontreeitemclick" @check="checkAction" :default-expanded-keys="['marker', 'polyline', 'polygon']">
                <el-row style="margin: 0; padding: 0" slot-scope="{ node, data }">
                   <!-- <el-popover v-if="!data.children" placement="top" trigger="manual">
                        <el-button v-for="tool in tools" :key="tool.id" @click="tool.action(data)">
                            <i class="iconfont action-item" :class="[tool.icon]"></i>
                        </el-button>-->
                        
                        <el-col slot="reference" :span="24" style="text-align: left">
                            <i :class="data.icon" class="action-item"></i>

                            
                            <span class="node-name action-item">{{ data.text }}</span>
                        </el-col>
                   <!-- </el-popover> -->
                    <el-col  :span="24" style="text-align: left">
                        <i :class="data.icon" class="action-item"></i>



                        <span class="node-name action-item" @click="clicktree">{{ data.text }}</span>
                    </el-col>
                </el-row>
            </el-tree>
        </el-main>

        <!--
        <el-dialog title="新建任务" :visible.sync="taskDialogVisible" append-to-body>
            <el-form :model="taskModel">
                <el-form-item label="任务名称">
                    <el-input v-model="taskModel.name" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="taskDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="taskDialogVisible = false">确 定</el-button>
            </div>
        </el-dialog>
        -->
    </el-container>
</template>
<script>
import { saveAs } from "file-saver";
import GraphicManager from "../../../plugins/mev/draw/core/GraphicManager";
import MarkerManager from "../../../plugins/mev/draw/core/MarkerManager";


//引入全局函数
import { globalBus } from '../../../plugins/mev/draw/utils/globalbus';

export default {
    data() {
        return {
            markerTree: new Map(),
            polylineTree: new Map(),
            polygonTree: new Map(),
            labelTree: new Map(),
            modelTree: new Map(),
            renameNodeStatus: false,
            curselnode:{empty:true},
            showpopupmenu:false,
            left:0,
            top:0,
            checked: [],
            newName: "",
            json: [
                {
                    id: "marker",
                    text: "标记",
                    type: "marker",
                    icon: "iconfont icon-lujing",
                    children: []
                },
                {
                    id: "polyline",
                    text: "线",
                    type: "polyline",
                    icon: "iconfont iconpolyline",
                    children: []
                },
                {
                    id: "polygon",
                    text: "多边形",
                    type: "polygon",
                    icon: "iconfont iconpolygon",
                    children: []
                }
                // {
                //     id: "label",
                //     text: "文字",
                //     type: "label",
                //     icon: "iconfont iconlabel",
                //     children: []
                // },
                // {
                //     id: "model",
                //     icon: "iconfont iconmodel",
                //     text: "模型",
                //     type: "model",
                //     children: []
                // }
            ],
            defaultTools: {
                locate: { text: "定位", icon: "iconlocate", action: this.locate },
                rename: {
                    text: "重命名",
                    icon: "iconrename",
                    action: this.renamefrompanel
                },
                edit: { text: "编辑", icon: "iconedit", action: this.edit },
                drop: { text: "删除", icon: "iconremove", action: this.dropex }
            },
            taskDialogVisible: false,
            taskModel: {
                name: "default",
                type: ""
            }
        };
    },
    props: {
        tools: {
            default: function() {
                return this.defaultTools;
            }
        }
    },
    mounted() {},
    computed: {},
    methods: {
        init() {
            // do nothing

            if(window.popupdict == null)
            window.popupdict = new Map();

   
           let that = this;
                  globalBus.$on('deletelayernode', (id) => {
       // console.log(`brother 被点击了 ${number} 次。`);
       that.dropid(id);
      });
        },

        //点击树事件 用来计算弹出菜单位置
        clicktree(e)
        {
            
            this.top =  e.clientY - document.documentElement.clientHeight * 0.12;
            this.left = -10

            //console.log('click tree',e,e.offsetY,this.top,this.left);
        },

        //弹出菜单用 

        ontreeitemclick(e)
        {

            // console.log(e.pageX,e.pageY);
            this.showpopupmenu = true;

            this.curselnode = e;

            if(e.children)
            {
                this.curselnode = {empty:true};
                this.showpopupmenu = false;
            }

            //console.log("clicked",this.curselnode);
        },
        checkAction(data, node) {



            if (data.id === "polygon") {
                if (data.children && data.children.length > 0) {
                    data.children.forEach(item => {
                        if (node.checkedKeys.includes("polygon")) {
                            this.$emit("select", item.id, true);
                        } else {
                            this.$emit("select", item.id, false);
                        }
                    });
                }
                return;
            }
            if (node.checkedKeys.includes(data.id)) {

               /* for(var [key,value] of window.popupdict)
                {
                    if(value == true)
                    {

                        alert("select" + key + " " + false)
                        
                        this.$emit("select", key, false);
                        window.popupdict.set(key,false);
                    }
                }

                alert("select" + data.id)*/

                this.$emit("select", data.id, true);

               // window.popupdict.set(data.id,true);
            } else {
                this.$emit("select", data.id, false);


             //   window.popupdict.set(data.id,false);
            }
        },
        //弹出菜单 飞到功能
        locate(data) {
            
            this.showpopupmenu = false;

            if(this.curselnode.empty ==true)
            return;
            var data = this.curselnode;
            this.$emit("locate", data.id);
        },
        renamefrompanel(data,id,text)
        {

            if(this.curselnode.empty ==true)
            return;
            var data = this.curselnode
            //alert("准备重命名"+ JSON.stringify(this.curselnode));
            if (data) {
                this.$set(data, "edit", true);
                this.newName = data.text;
               // alert(window.fromupdate)



               this.taskDialogVisible =true;
                
                
            }

        },
        rename(data, id, text) {
            // data.edit=true;
           //alert('开始改名？')
            if(this.curselnode.empty ==true)
            return;
            var data = this.curselnode
            //alert("准备重命名"+ JSON.stringify(this.curselnode));
            if (data) {
                this.$set(data, "edit", true);
                this.newName = data.text;
               // alert(window.fromupdate)



               
                
                
            }
            // else {
            //     for (let ls of this.json) {
            //         for (let l of ls.children) {
            //             if (l.id === id) {
            //                 l.text = text;
            //             }
            //         }
            //     }
            // }
        },


        //弹出菜单 重命名
        renameAction(data) {
            this.showpopupmenu = false;

            if(this.curselnode.empty ==true)
            return;

            //alet("inside renameAction")

//  window.fromupdate = false;

            var data = this.curselnode
            data.edit = false;
            this.$emit("rename", data.id, this.newName);
            data.text = this.newName;
            this.taskDialogVisible = false;
            
        },

        //弹出菜单 编辑
        edit(data) {
            this.showpopupmenu = false;
            if(this.curselnode.empty ==true)
            return;
            var data = this.curselnode;
            this.$emit("edit", data.id);
        },
        dropid(id) {

            //alert(id)
            if (!id) return;
            this.$emit("delete",id);
            const index = this.checked.indexOf(id);
            if (id > -1) {
                this.checked.splice(index, 1);
            }
            this.$nextTick(() => {
                this.$refs.tree.setCheckedKeys(this.checked);
            });

            for (let ls of this.json) {
                let i = 0;
                for (let l of ls.children) {
                    if (l.id === id) {
                        ls.children.splice(i, 1);
                        break;
                    }
                    i++;
                }
            }
        },
         //弹出菜单 再删除
         dropex(data)
         {

             //alert("enter ex  ???" + data);
             this.showpopupmenu = false;

            if(this.curselnode.empty ==true)
            return;

            data = this.curselnode;
            if (!data) return;
            this.dropid(data.id);
             
         },

        //弹出菜单 删除
        drop(data) {

           // alert("enter  ???" + data);
            this.showpopupmenu = false;

            if(this.curselnode.empty ==true)
            return;

            data = this.curselnode;
            if (!data) return;
            this.dropid(data.id);
        },
        //
        removeAll() {
            this.showpopupmenu = false;
            this.$emit("clear");
            for (let ls of this.json) {
                ls.children.splice(0);
            }
            this.$nextTick(() => {
                this.$refs.tree && this.$refs.tree.setCheckedKeys([]);
            });
           if(window.managers != null)
            window.managers.clear();
        },
        insertLayer(type, id, name) {
            name = name || "未命名";
            this.json[type].children.push({
                id: id,
                text: name,
                icon: "el-icon-document"
            });
            this.checked.push(id);
            this.$nextTick(() => {
                this.$refs.tree.setCheckedKeys(this.checked);
            });
        },
        exportHandler(cmd) {
            if (this.taskModel.name == "无任务") {
                this.$message("请新建任务");
                return;
            }
            const json = {
                type: "FeatureCollection",
                name: "graphic",
                crs: {
                    type: "name",
                    properties: { name: "urn:ogc:def:crs:OGC:1.3:CRS84" }
                },
                features: []
            };
            let fcount = 0;
            let managers = window.manager.values();
            for (let m of managers) {
                json.features.push(m.toGeoJson());
                fcount += 1;
            }
           /* managers = window.manager.values();
            for (let m of managers) {
                json.features.push(m.toGeoJson());
                fcount += 1;
            }*/
            if (fcount <= 0) {
                this.$message("请进行标注后再保存");
                return;
            }
            let that = this;

           // alert(JSON.stringify(json));

            JsContext.onMarkGeoJsonExport = function(path) {
                json.taskModel = that.taskModel;
                path = path + "/" + that.taskModel.name + ".geojson";
                JavaContext.write(path, JSON.stringify(json));
                that.$message(path);
            };
            //var path = '/storage/emulated/0/mev/' + that.taskModel.name + ".geojson";
           // alert(path);
           // JavaContext.write(path, JSON.stringify(json));
            //write
           // alert(that.taskModel.name);
            //var path = '/storage/emulated/0/mev/' + that.taskModel.name + ".geojson";

            //存在固定位置
            JsContext.onMarkGeoJsonExport('/storage/emulated/0/mev')
            //JavaContext.write(path, JSON.stringify(json));
            //JavaContext.loadFileBrowser(false, "/storage/emulated/0/mev", true, "JsContext.onMarkGeoJsonExport");
        },
        importHandler(cmd) {
            window.isimporting = true;
            this.showpopupmenu = false;
            let that = this;
            JsContext.onMarkGeoJsonImport = function(path) {
                let jsonObj = null;
                try {
                    const str = JavaContext.ReadTxtFile(path);
                   // alert(str);
                    if (str.length > 1) {
                        jsonObj = JSON.parse(str);
                    }
                } catch (e) {
                    that.$message(e.message);
                }
                if (jsonObj == null) {
                    that.$message("导入失败:" + path);
                    return;
                }

                that.removeAll();

                const features = jsonObj.features;
               
                for (let feat of features) {


                    // alert('元素个数:',JSON.stringify(feat));
                    if (feat.geometry.type.toUpperCase() === "POINT") {

                       
                        MarkerManager.INSTANCE.import(feat);
                    } else {
                        GraphicManager.INSTANCE.import(feat);
                    }
                }
                if (jsonObj.taskModel) {
                    that.taskModel.name = jsonObj.taskModel.name;
                }

                 window.isimporting = false;
                that.$message("导入成功:" + path);
            };
            //从固定位置读取
            var path = '/storage/emulated/0/mev/' + that.taskModel.name + ".geojson";
            JsContext.onMarkGeoJsonImport(path);
            //JavaContext.loadFileBrowser(true, "/storage/emulated/0/mev", true, "JsContext.onMarkGeoJsonImport");
        },
        closeLayerManaer() {
            this.$emit("close");
        },
        newHandler() {
            this.taskDialogVisible = true;
        }
    }
};
</script>

<style scoped>
.el-container {
    color: #ffffff;
}

.el-header {
    line-height: 40px;
}

.el-main {
    margin: 0;
    padding: 0;
}

.popmenu{
height: 4vh;
width: 20vw;
position:absolute;
z-index:999; 

}
</style>
